package controller.v2;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import model.DicVO;
import model.LogOrder;
import model.MemberVO;
import model.OrderTimer;
import model.OrderVO;
import model.StandardVO;
import model.UorderCaseVO;
import model.UorderGoodVO;
import model.UorderVO;
import service.v2.ApplyReturnService;
import service.v2.GoodTempService;
import service.v2.MemberService;
import service.v2.OrderCancelService;
import service.v2.OrderService;
import service.v2.PushService;
import service.v2.SplitService;
import service.v2.UorderService;
import util.DeliverUtil;
import util.PackageUtil;
import util.PropertieUtil;

@Controller
@RequestMapping("/v2/order")
public class OrderController {
	
	@Autowired
	private OrderService orderService;
	@Autowired
	private MemberService memberService;
	@Autowired
	private UorderService uorderService;
	@Autowired
	private ApplyReturnService applyReturnService;
	@Autowired
	private GoodTempService goodTempService;
	
	/** 
	 *  订单列表
	 * @param token
	 * @param member_id
	 * @param memberVO
	 * @param state
	 * @param orderVO
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getNewOrderList",method=RequestMethod.GET) 
	public Object getNewOrderList (
			@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)String member_id,
			@RequestParam(value="state", defaultValue="0", required=false) String state,
			MemberVO memberVO,
			UorderVO orderVO,
			@RequestHeader(value="LANG", required=false)String lang) throws Exception{	
		
		MemberVO member = memberService.getLoginMemberById(member_id);
		orderVO.setCreate_by(member_id);
		orderVO.setState(state);
		String country = null;
		if(lang==null){
			country = "1";
		}else{
			country = "0";
		}
		orderVO.setCountry(country);
		//检查定时器
		uorderService.dealPersonTimer(member_id);
		int total = uorderService.getTotal(orderVO);
		orderVO.setPagination(orderVO.getPage_index(), total + "");
		List<UorderVO> orderList = uorderService.getOrderList(orderVO);
		
		Map map = new HashMap();
		map.put("pagination", orderVO);
		map.put("list", orderList);
		map.put("free_balance", member.getFree_cash());
		map.put("cash_balance",member.getGood_cash());
		  
		return PackageUtil.packageParams(200,"successs",map,"");
	}
	
	/**
	 *  订单详情
	 * @param token
	 * @param member_id
	 * @param memberVO
	 * @param order_id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getNewOrderDetails",method=RequestMethod.GET) 
	public Object getNewOrderDetails(
			@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)String member_id,
			@RequestParam(value="order_id",required=false)String order_id,
			MemberVO memberVO) throws Exception{
			Map<String, Object> map = new HashMap<String, Object>();
			uorderService.dealPersonTimer(member_id); 
			MemberVO member = memberService.getLoginMemberById(member_id);
			UorderVO orderVO = uorderService.getOrderDetails(order_id);
			map.put("free_balance", member.getFree_cash());
			map.put("cash_balance", member.getGood_cash());
			map.put("data", orderVO);
		return  PackageUtil.packageParams(200,"successs",map,"");
	}
	
	/**
	 *   未付款取消订单
	 * @param token
	 * @param member_id
	 * @param order_id
	 * @param order_timer_id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/cancelOrderBeforePay",method=RequestMethod.POST) 
	public Object cancelOrderBeforePay (@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)String member_id,
			String order_id,String order_timer_id) throws Exception{	
		if(order_id==null||"".equals(order_id) || order_timer_id==null||"".equals(order_timer_id)){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}
		UorderVO order = uorderService.getOneOrderById(order_id);
		if(order==null){
			return PackageUtil.packageParams(10905,"订单不存在","",""); 
		}
		if(!order.getState().equals("1")&&!order.getState().equals("2")){
			return PackageUtil.packageParams(10906,"订单状态异常","",""); 
		}		
		uorderService.UorderCalcelNoPayBySelf(order_id,order_timer_id,order.getTicket_status(),order.getPay_type(),order.getCreate_by());	
		return PackageUtil.packageParams(200,"successs","","");
	}
	
	/**
	 * 
	 * 付款以后申请取消包裹
	 * @param token
	 * @param member_id
	 * @param memberVO
	 * @param case_id
	 * @param order_id
	 * @param cancel_reason
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/cancelPaidOrder",method=RequestMethod.POST) 
	public Object cancelPaidOrder(
			@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)String member_id,
			@RequestParam(value="case_id",required=false)String case_id,
			@RequestParam(value="order_id",required=false)String order_id,
			@RequestParam(value="cancel_reason",required=false)String cancel_reason,
			MemberVO memberVO) throws Exception{	
		
		if(case_id==null||"".equals(case_id) ||order_id==null||"".equals(order_id) || cancel_reason==null||"".equals(cancel_reason)){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}
		
		boolean state = orderService.judgeState(order_id,"3");
		if(state==false){
			return PackageUtil.packageParams(10906,"订单状态异常","",""); 
		}
		UorderCaseVO orderCase  = uorderService.getOrderCaseById(case_id);
		if(orderCase==null){
			return PackageUtil.packageParams(10919,"包裹不存在","",""); 
		}
		if(!"3".equals(orderCase.getState())){
			return PackageUtil.packageParams(10920,"包裹状态异常","",""); 
		}
		
		uorderService.cancelPaidOrder(order_id,case_id,cancel_reason,member_id,orderCase);
		return PackageUtil.packageParams(200,"successs","","");
	}
	
	/**
	 *  获取取消包裹log
	 * @param token
	 * @param member_id
	 * @param memberVO
	 * @param case_id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getCancelCaseLog",method=RequestMethod.GET) 
	public Object getCancelCaseLog(
			@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)String member_id,
			@RequestParam(value="case_id",required=false)String case_id,
			MemberVO memberVO) throws Exception{	
		if(case_id==null||"".equals(case_id) ){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}
		List<LogOrder> caseLog = uorderService.getCancelCaseLog(case_id);
		return PackageUtil.packageParams(200,"successs",caseLog,"");
	}
	
	/**
	 * 	查看快递(包裹)
	 * @param case_id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/viewLogistics",method=RequestMethod.GET) 
	public Object viewLogistics(String case_id) throws Exception{	
		
		if(case_id==null||"".equals(case_id) ){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}
		
		UorderCaseVO orderCase = uorderService.getOrderCaseById(case_id);
		if(orderCase==null){
			return PackageUtil.packageParams(10919,"包裹不存在","",""); 
		}
		UorderVO order = uorderService.getOneOrderById(orderCase.getOrder_id());
		String code = null;
		if(order.getCountry().equals("1")){
			code = PropertieUtil.loadPropertie("express_delivery");
		}else if(order.getCountry().equals("0")){
			code = PropertieUtil.loadPropertie("inter_ems_name");
		}
		String com = "";
		String no = orderCase.getEms_no();
		String name = "";
		List<DicVO>  dicList = applyReturnService.getDicByParentId(code);
		for (DicVO dic :dicList) {
			if(dic.getDic_id().equals(orderCase.getEms_id())){
				com = dic.getOther();
				name =  dic.getName();
			}
		}
		if(com!=""&&no!=null&&no!=""){
			JSONObject deliver = DeliverUtil.getDeliverMsg(com, no,name);
			if("200".equals(deliver.get("resultcode"))){
				JSONObject resutObj = JSON.parseObject(deliver.get("result").toString());
				JSONArray list = JSON.parseArray(resutObj.get("list").toString());
				//Collections.reverse(list);
				resutObj.put("list", list);
				deliver.put("result", resutObj);
				deliver.put("if_msg", "You can track your order from "+name+" website");
				return PackageUtil.packageParams(200,"successs",deliver,"");
			}else{
				Map map = new HashMap();
				map.put("no", no);
				map.put("name", name);
				map.put("send_time", orderCase.getSend_time()==null?"":orderCase.getSend_time());
				String if_msg = "";
				if("1".equals(order.getCountry())){
					if_msg = "您的订单已提交仓库处理";
				}else if("0".equals(order.getCountry())){
					if_msg = "You can track your order from "+name+" website";
				}
				map.put("if_msg", if_msg);
				return PackageUtil.packageParams(200,"快递不存在",map,"");
			}
		}else{
			return PackageUtil.packageParams(10916,"快递不存在","","");
		}
	}
	
     /**
      * 确认收货(包裹)
      * @param token
      * @param case_id
      * @return
      * @throws Exception
      */
	@ResponseBody
	@RequestMapping(value="/caseConfirm",method=RequestMethod.POST) 
	public Object caseConfirm(
			@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)String member_id,
			MemberVO memberVO,String case_id) throws Exception{
		if(case_id==null||"".equals(case_id)){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}
		UorderCaseVO orderCase  = uorderService.getOrderCaseById(case_id);
		if(orderCase==null){
			return PackageUtil.packageParams(10919,"包裹不存在","",""); 
		}
		if(!"4".equals(orderCase.getState())){
			return PackageUtil.packageParams(10920,"包裹状态异常","",""); 
		}	
		UorderVO order = uorderService.getOneOrderById(orderCase.getOrder_id());
		if(order==null){
			return PackageUtil.packageParams(10905,"订单不存在","",""); 
		}
		boolean state = uorderService.caseConfirm(orderCase);
		//订单变成交易成功了 （需要分润）
		if(state){
			int orderBackCount = orderService.checkOrderBackState(orderCase.getOrder_id());
			uorderService.conFirmOrderShareBenifit(orderBackCount, order.getTicket_status(), order.getOrder_type(), order.getId());
		}
		return PackageUtil.packageParams(200,"success","","");
	}
	
	/**
	 *  交易成功信息(包裹) 
	 * @param token
	 * @param member_id
	 * @param memberVO
	 * @param case_id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getConfirmMsg",method=RequestMethod.GET) 
	public Object getConfirmMsg(
			@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)String member_id,
			MemberVO memberVO,String case_id) throws Exception{
		if(case_id==null||"".equals(case_id)){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}
		UorderCaseVO orderCase  = uorderService.getOrderCaseById(case_id);
		if(orderCase==null){
			return PackageUtil.packageParams(10919,"包裹不存在","",""); 
		}
		if(!"5".equals(orderCase.getState())){
			return PackageUtil.packageParams(10920,"包裹状态异常","",""); 
		}	
		UorderVO order = uorderService.getConfirmMsg(case_id);
		return PackageUtil.packageParams(200,"success",order,"");
	}
	
	
	/**
	 * 获取包裹评价
	 * @param token
	 * @param member_id
	 * @param memberVO
	 * @param case_id
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/getCaseEvaluate",method=RequestMethod.GET) 
	public Object getCaseEvaluate(
			@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)String member_id,
			MemberVO memberVO,String case_id) throws Exception{
		if(case_id==null||"".equals(case_id)){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}
		List<UorderGoodVO> orderGoodList = uorderService.getCaseEvaluate(case_id);
		return PackageUtil.packageParams(200,"success",orderGoodList,"");
	}
	
	/**
	 *  提交包裹评价
	 * @param token
	 * @param member_id
	 * @param case_id
	 * @param standard_id
	 * @param text
	 * @param imgs
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value="/subCaseEvaluate",method=RequestMethod.POST) 
	public Object subCaseEvaluate(
			@RequestHeader (value="AUTHORIZATION", required=false) String token,
			@RequestHeader (value="SECRET", required=false)String member_id,
			String case_id,String order_good_id,String text,String imgs) throws Exception{
		if(case_id==null||"".equals(case_id)||order_good_id==null||"".equals(order_good_id)||text==null||"".equals(text)){
			return PackageUtil.packageParams(10001,"缺少必选参数","","");
		}
		List<UorderGoodVO> orderGoodList = uorderService.subCaseEvaluate(case_id,order_good_id,text,imgs,member_id);
		return PackageUtil.packageParams(200,"success",orderGoodList,"");
	}
	
	/**
	 * 订单删除
	 * @param token
	 * @param member_id
	 * @param memberVO
	 * @param order_id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/uorderDelete",method=RequestMethod.POST) 
	public Object orderDelete (@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)String member_id,
			MemberVO memberVO,@RequestParam(value="order_id",required=false)String order_id){	
		boolean state1 = orderService.judgeState(order_id,"6");
		boolean state2 = orderService.judgeState(order_id,"5");
		if(state1==false&&state2==false){
			return PackageUtil.packageParams(10906,"订单状态异常","",""); 
		}
		orderService.OrderDelete(order_id);
		return PackageUtil.packageParams(200,"successs","","");
	}
	
	/**
	 * 算运费
	 * @param standard_id
	 * @param num
	 * @param address_id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/getFreight",method=RequestMethod.GET) 
	public Object getFreight (String standard_id,String num,String address_id){	
		String[] standards = standard_id.split(",");
		String[] numes = num.split(",");
		double freight = goodTempService.getFreightByCity(standards, numes, address_id);
		return PackageUtil.packageParams(200,"successs",freight,"");
	}
	
	@ResponseBody
	@RequestMapping(value="/getStandardById",method=RequestMethod.GET) 
	public Object getStandardById (@RequestHeader (value="AUTHORIZATION", required=false) String token,@RequestHeader (value="SECRET", required=false)String member_id,
			@RequestParam(value="standard_id",required=false)String standard_id){	
		if(standard_id==null||"".equals(standard_id)){
			return PackageUtil.packageParams(10001,"缺少必选参数","",""); 
		}	
		StandardVO standard = orderService.getStandardById(standard_id);
		if(standard==null){
			return PackageUtil.packageParams(10101,"商品已下架或删除","",""); 
		}
		return PackageUtil.packageParams(200,"successs",standard,"");
	}
	
	
}
